<script setup lang="ts">
import { request } from '@/api'
import imgSlot from '@/components/imgSlot.vue'
import { closeToast, showLoadingToast, showToast, type ActionSheetAction } from 'vant'
import { onMounted, ref } from 'vue'
import base64ToBlob from 'b64-to-blob'
import { showConfirmDialog } from 'vant'
import { useRoute, useRouter } from 'vue-router'
// -------------表单回显-----------------------
// 用户数据
const user = ref<User>({} as User)
const token = ref('')
// 获取用户数据
onMounted(async () => {
  showLoadingToast({ message: '加载中...', duration: 0, forbidClick: true })
  token.value = gg.getToken()
  const res = await request.get<GGResponse<User>>('/v1_0/user/profile')
  user.value = res.data.data
  closeToast()
})

// ------------------------修改头像-------------------------

// 是否显示拍照相册交互弹框
const showAvatarSheet = ref(false)
// 选项
const actions = [{ name: '拍照' }, { name: '本地选择' }]
// 点击取消
const onCancel = () => showToast('取消')
const onSelect = async (action: ActionSheetAction, index: number) => {
  // console.log(action, index)
  if (index === 0) {
    // 拍照
    alert('该功能暂未开放')
  } else if (index === 1) {
    // 本地选择
    console.log('本地选择')
    const data = await gg.pickerPhoto() //base64
    await onUpdateAvatar(data)
  }
}
//  头像上传
const onUpdateAvatar = async (data: string) => {
  try {
    showAvatarSheet.value = false
    showLoadingToast({ message: '正在上传', duration: 0, forbidClick: true })
    // base64 to
    const image = base64ToBlob(data, 'image/jpeg')
    // 创建一个formdata对象
    const fd = new FormData()
    // formData.append(name, value, filename);
    // name:value 中包含的数据对应的表单名称。【file】
    // value：表单的值 /数据【image】
    // filename：传给服务器的文件名称， File 对象的默认文件名是该文件的名称【Date.now() + '.jpeg'】
    fd.append('photo', image, Date.now() + '.jpeg')

    // 调用上传接口。根据接口文档设置地址和方法，formData设置到参数2，上次完毕用户头像就更新了
    const res = await request.patch<GGResponse<{ id: string; photo: string }>>(
      '/v1_0/user/photo',
      fd,
    )
    // 打印上传数据
    // alert(res.data.data.photo)
    // 重新发送请求获取用户数据
    token.value = gg.getToken()
    const userRes = await request.get<GGResponse<User>>('/v1_0/user/profile')
    const userData = userRes.data.data
    // 更新h5用户信息
    user.value = userData
    // 更新鸿蒙端的头像-自动更新
    showToast({ message: '上传成功' })
  } catch (err) {
    showToast({ message: '上传失败' + err })
    console.log({ message: '上传失败' + err })
  }
}
// 点击退出
const clickOut = () => {
  showConfirmDialog({
    title: '标题',
    message: '如果解决方法是丑陋的，那就肯定还有更好的解决方法，只是还没有发现而已。',
  })
    .then(() => {
      gg.logoutApi()
    })
    .catch(() => {
      // on cancel
    })
}
// 获取当前页面对应的路由对象
const route = useRouter()
const changeName = () => {
  route.push({
    path: '/changeName',
    query: { name: user.value.name },
  })
}
</script>

<template>
  <div class="profile-edit-page">
    <!-- 中间表单部分 -->
    <van-cell-group style="width: 100%">
      <!-- 头像 使用插槽  imgSlot -->
      <imgSlot>
        <span @click="showAvatarSheet = true">
          <van-image round width="25px" height="25px" :src="user.photo" />
        </span>
      </imgSlot>
      <!-- value  number | string -->
      <van-cell title="昵称" is-link :value="user.name" @click="changeName" />
      <van-cell title="简介" is-link :value="user.intro" />
    </van-cell-group>
    <div style="height: 20px" class="class-name"></div>

    <van-cell-group style="width: 100%">
      <!-- value  number | string -->
      <van-cell title="性别" is-link :value="user.gender" />
      <van-cell title="生日" is-link :value="user.birthday" />
    </van-cell-group>

    <van-cell title=" " style="width: 100%; height: 200px" />
    <!-- 头像弹层 -->
    <van-action-sheet
      v-model:show="showAvatarSheet"
      :actions="actions"
      cancel-text="取消"
      close-on-click-action
      @cancel="onCancel"
      @select="onSelect"
      :style="{ paddingBottom: '40px' }"
    />

    <div class="submit">
      <span @click="clickOut">退出登录</span>
    </div>
  </div>
</template>

<style lang="css" scoped>
.profile-edit-page {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-end; /* 将子元素推到容器底部 */
  align-items: center; /* 实现子元素水平居中 */
}
.class-name {
  background-color: rgb(245, 245, 245);
}
.class-name2 {
  background-color: white;
}

.submit {
  padding: 16px;
  color: #ddad0e;
  font-weight: 600;
}
</style>
